#!/usr/bin/env python3
# -*- coding: utf8 -*-

'''
This is a simple command-line utility for modifying
musepack chapters

LICENCE: GPLv2
AUTHOR: Joseph Botosh <rumly111@gmail.com>
'''

import mpcchap
import getopt, sys, os
import tempfile
import configparser
import subprocess

import chapfile

USAGE = '''\
Usage:
    {} [OPTIONS]
Options may be:
    [  -h | --help ]
    [ [-s | --source] <chapter-source> ]
    [ [-c | --encoding] <source-encoding> ]
    [ [-m | --mpc ] <mpc-file> ]
    [ [-e | --editor] <editor> ]
    [  -p | --print ]
'''.format(sys.argv[0])

try:
    opts, args = getopt.getopt( sys.argv[1:],
                                'hs:m:e:pc:',
                               ['help','source=',
                                'mpc=','editor=',
                                'print','encoding='] )
except getopt.GetoptError:
    print(USAGE)
    sys.exit(2)

if len(sys.argv) == 1:
    print(USAGE)
    sys.exit(0)


just_print = False  # Just print chapters and exit
mpc = ''
source = ''
encoding=None
# editor = '/usr/bin/vim'
editor = os.getenv('EDITOR')

for o, a in opts:
    if o in   ('-h','--help'):
        print(USAGE)
        sys.exit(0)
    elif o in ('-s','--source'):
        source = a
    elif o in ('-m','--mpc'):
        mpc = a
    elif o in ('-e','--editor'):
        editor = a
    elif o in ('-p','--print'):
        just_print=True
    elif o in ('-c','--encoding'):
        encoding=a

##print('Using editor {}'.format(editor))

if not os.path.exists(mpc):
    print('MPC file "{}" does not exist !'.format(mpc))
    sys.exit(3)

# Checking source existance
if source == '':
    source = mpc
if not os.path.exists(mpc):
    print('Source file "{}" does not exist !'.format(source))
    sys.exit(3)

chapters = chapfile.ChapterFileParser()
chapters.read_chapters_from(source,encoding)

if just_print:
    chapters.write_chap_file('/dev/stdout')
    sys.exit(0)

chap_name = tempfile.mktemp(suffix='.chap', prefix='mpcc-')
chapters.write_chap_file(chap_name)

# Edit common tags with external editor
subprocess.call([editor,chap_name])

chapters.read_chap_file(chap_name)

answer = input('Write chapters to "{}" ? [yes] '.format(mpc))
if answer.lower() in ('y','yes'):
    chapters.write_chapters_to_mpc(mpc)

